import requests
import re
import io
from PIL import Image

def get_image(driver,image_div_xpaths):
    '''
    获取图片
    :param driver:
    :param image_div_xpaths:
    :return:
    '''
    image_divs = driver.find_elements_by_xpath(image_div_xpaths)
    #匹配图片url
    img_url_list = re.findall('background-image: url\(\"(.*?)\"\);',image_divs[0].get_attribute('style'))
    img_url = img_url_list[0]
    img_url.replace('webp','jpg')
    req = requests.get(img_url)

    #图片写入内存
    image_file = io.BytesIO(req.content)

    #获取每个小图的坐标
    position_list = []
    for image_div in image_divs:
        position = {}
        match = re.findall('background-position: (.*)px(.*)px',image_div.get_attribute('style'))
        position['x'] = int(match[0][0])
        position['y'] = int(match[0][1])
        position_list.append(position)

    image = restore_image(image_file,position_list)
    return image

def restore_image(file,position_list):
    '''
    还原图片
    :param file:二进制文件
    :param position_list:被分割的小图坐标
    :return:
    '''
    img = Image.open(file)
    up_img_list = []
    down_img_list = []

    #把打乱的图片切割成小块
    for position in position_list:
        if position['y'] ==-58:
            up_img_list.append(img.crop((abs(position['x']),58,abs(position['x'])+10,116)))
        elif position['y'] == 0:
            down_img_list.append(img.crop((abs(position['x']),0,abs(position['x']+10),58)))

    new_img = Image.new('RGB',(260,116))

    #根据div中图片顺序将小图依次粘贴
    x_offset = 0
    for img in up_img_list:
        new_img.paste(img,(x_offset,0))
        x_offset += img.size[0]

    for img in down_img_list:
        new_img.paste(img,(x_offset,58))
        x_offset += img.size[0]

    return  new_img

def get_diffrent_loaction(img1,img2):
    '''
    寻找缺口x坐标
    :param img1:
    :param img2:
    :return:
    '''
    x = 0
    for x in range(0,260):
        for y in range(0,116):
            if not_similar(img1,img2,x,y):
                return x

def not_similar(img1,img2,x,y):
    '''
    对比RGB值
    :param img1:
    :param img2:
    :param x:
    :param y:
    :return:
    '''
    #根据传入的坐标获得图片rgb
    pixel1 = img1.getpixel((x,y))
    pixel2 = img2.getpixel((x,y))

    for n in range(0,2):
        if abs(pixel1[n])-abs(pixel2[n])>55: #55是一个模糊值
            return True
    return False
